<template>
  <div class="create-ip-order">
    <Title title="订单信息" class="mb-16" />
    <div v-loading="loading" class="create-ip-order-form">
      <el-form
        ref="formRef"
        :model="paramsObj"
        :rules="rules"
        :label-position="formAlign"
        class="edit-order lineHeight32"
        label-width="105px">
        <div class="one-cell color999">
          <el-form-item label="订单类型：" prop="orderType" style="margin-bottom:20px;">商务订单</el-form-item>
        </div>
        <el-row class="response-el-row" type="flex">
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="IP形象" prop="ipAry">
              <selectWithUserLoad
                ref="selectUser"
                v-model="paramsObj.ipAry"
                :disabled="isEdit"
                :select-data-list="paramsObj.ipAry || []"
                :hide-select-list="paramsObj.ipAry || []"
                :loadmore-method="getipFigure()"
                multiple
                placeholder="请选择IP形象"
                value-type="object"
                key-name="ipId"
                label-name="ipNameAndSeries"
                filterable
                collapse-tags
                clearable
                class="width240"
                @change="ipFigureChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="签约年度" prop="signYear">
              <el-date-picker
                v-model="paramsObj.signYear"
                :clearable="false"
                :editable="false"
                type="year"
                placeholder="请选择签约日期"
                value-format="timestamp"
                size="small"
                class="order-time width240"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="下单日期" prop="orderTime">
              <el-date-picker
                v-model="paramsObj.orderTime"
                :clearable="false"
                :editable="false"
                type="date"
                placeholder="“请选择签约日期"
                value-format="timestamp"
                size="small"
                class="order-time width240"
                format="yyyy/MM/dd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="销售" prop="market">
              <selectWithUserLoad
                ref="selectUser"
                v-model="paramsObj.marketObj"
                :hide-select-list="paramsObj.marketObj && JSON.stringify(paramsObj.marketObj) !== '{}' ?[paramsObj.marketObj] : []"
                :select-data-list="paramsObj.marketObj && JSON.stringify(paramsObj.marketObj) !== '{}' ?[paramsObj.marketObj] : []"
                :multiple="false"
                placeholder="请选择商务负责人"
                value-type="object"
                extend-class="create-ip-order-select"
                key-name="id"
                label-name="userName"
                show-check-user
                filterable
                collapse-tags
                class="width240"
                @change="marketChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="客户名称" prop="clientName">
              <selectWithUserLoad
                ref="selectUser"
                v-model="paramsObj.clientObj"
                :hide-select-list="paramsObj.clientObj ?[paramsObj.clientObj] : []"
                :select-data-list="paramsObj.clientObj ?[paramsObj.clientObj] : []"
                :multiple="false"
                :loadmore-method="getClient()"
                placeholder="请选择客户"
                value-type="object"
                extend-class="create-ip-order-select width-long-item"
                key-name="id"
                label-name="clientName"
                filterable
                collapse-tags
                class="width240"
                @change="clientNameChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="客户来源" prop="clientOriginId">
              <el-select v-model="paramsObj.clientOriginId" placeholder="请选择客户来源" clearable filterable size="small" class="width240">
                <el-option
                  v-for="item in clientOrigin"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="合作类型" prop="themeId">
              <el-select v-model="paramsObj.themeId" placeholder="请选择合作类型" clearable filterable size="small" class="width240" @change="handleTheme">
                <el-option
                  v-for="item in theme"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="合作品类" prop="areaId">
              <el-select v-model="paramsObj.areaId" placeholder="请选择合作品类" clearable filterable size="small" class="width240" @change="handleArea">
                <el-option
                  v-for="item in area"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="合作事项" prop="matters">
              <el-input
                v-model="paramsObj.matters"
                maxlength="500"
                placeholder="请输入合作事项"
                size="small"
                class="width240"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="首次BD日期" prop="firstBDTime">
              <el-date-picker
                v-model="paramsObj.firstBDTime"
                :clearable="false"
                type="date"
                placeholder="请选择首次BD日期"
                value-format="timestamp"
                size="small"
                class="width240"
                format="yyyy/MM/dd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="合作期限" prop="authorizeTime">
              <el-date-picker
                v-model="paramsObj.authorizeTime"
                :disabled="isEdit"
                type="daterange"
                range-separator="至"
                size="small"
                value-format="timestamp"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="width240"
                format="yyyy/MM/dd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="分期月份" prop="licenseTime">
              <el-date-picker
                v-model="paramsObj.licenseTime"
                :disabled="isEdit"
                type="monthrange"
                range-separator="至"
                size="small"
                value-format="timestamp"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="width240"/>
              <div class="tip-right">期数：{{ rangeTime }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="收入模式" prop="sharingModel">
              <el-select :disabled="isEdit" v-model="paramsObj.sharingModel" placeholder="请选择" size="small" class="width240">
                <el-option
                  v-for="item in sharingModelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="保底总额(元)" prop="minPriceTotal">
              <el-input
                v-model="paramsObj.minPriceTotal"
                :disabled="isEdit"
                oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
                name="minPriceTotal"
                type="number"
                placeholder="保底总额"
                size="small"
                class="width240"
                @change="numberInputChange('minPriceTotal')"
                @mousewheel.native.prevent
              />
              <div v-if="paramsObj.minPriceTotal && rangeTime && rangeTime!=='--'" class="tip-bottom">每期保底金额：{{ mathMinPrice }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="paramsObj.remark" placeholder="备注" maxlength="200" name="remark" type="text" size="small" class="width240" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="附件" prop="attachment" class="attachment">
              <div class="attachment-container">
                <upAttachment
                  ref="uploadImg"
                  :import-api="'/common/file/upload'"
                  :hide-confirm="true"
                  :is-disabled="isFileDisabled"
                  :file-list="paramsObj.attachment"
                  btn-text="上传文件"
                  @upProgress="upProgress"
                  @complateSetData="complateSetData"
                  @removeFileList="removeFileList" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="标签" prop="tag">
              <TagSelect v-model="paramsObj.tag" :collapse-tags="false" :module-type="TAG_MODULES.IMAGE_AUTH" class="width240" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <DetailTabs v-model="activeId" :tabs="tabs" style="margin-top: 8px;"/>
    <IncomeItem
      v-if="hasRouteAuth('mengli:iPOrder:incomeRead') || hasRouteAuth('mengli:iPOrder:incomeAdmin') || isAdmin"
      v-show="activeId === 0"
      v-model="paramsObj.incomeList"
      :has-add-auth="hasRouteAuth('mengli:iPOrder:incomeAdd') || isAdmin"
      :has-edit-auth="hasRouteAuth('mengli:iPOrder:incomeEdit') || isAdmin"
      :has-delete-auth="hasRouteAuth('mengli:iPOrder:incomeDelete') || isAdmin"
      :is-detail="!!orderId"
      :income-list-data="incomeListData"
      :show-count-fields="false"
      style="margin-top: 10px;"
      @freshData="getIncomeList"
      @editIcomeItem="editIcomeItem"
      @addIcomeItem="addIcomeItem"
      @deleteIcomeItem="deleteIcomeItem"
    />
    <!-- <Title title="成本信息" />
    <ipSupplier ref="ipSupplier"/> -->
    <costBreakdownComponent
      v-show="activeId === 1"
      ref="costBreakdownRef"
      :is-create="!!orderId"
      :order-id="orderId"
      :cost-belong-type="2"
      :is-mengli="true"
      :is-detail="false"
      style="margin-top: 10px;"/>
    <InvoiceAndContract
      v-show="activeId === 2"
      ref="ContractSelect"
      :show-empty="true"
      :is-edit="true"
      :title="'合同信息'"
      :sub-title="'关联合同'"
      :type="1"
      style="margin-top: 10px;"
      placeholder="请输入合同编号/合同名称" />
    <div v-show="activeId === 2" class="select-related-container" style="margin-top: 32px">
      <InvoiceAndContract
        ref="InvoiceSelect"
        :is-edit="true"
        :show-empty="true"
        :title="'发票信息'"
        :sub-title="'关联发票'"
        :is-disabled="false"
        :type="2"
        :hide-all-operation="true"
        show-invoice-amount-total
        style="margin-top: 10px;"
        target-keyword="no"
        placeholder="请输入发票编号/发票号码" />
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="beforeSubmit">保存订单</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
import Title from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import TagSelect from '@/components/Common/tagSelect';
// import ipSupplier from '@/components/Mengli/mengliOrder/createMengli/ipSupplier';
import costBreakdownComponent from '@/components/Cost/costList';
import upAttachment from '@/components/Common/upAttachment/index';
import {
  getIpImageList, getClientList, getMengliSuppliers,
  createMengliIpOrder, editMengliIpOrder, getipLicense,
  addIpIncomeList, editIpIncomeList, deleteIpIncomeList, getOrderConfig, getIpIncomeList
} from '@/api/mengliOrder';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import { validateIp, validateTime, validateNumber } from './validator/validator';
import { hasRouteAuth } from '@/utils/permission';
import { TAG_MODULES } from '@/utils/const';
import { mapState } from 'vuex';
import IncomeItem from '@/components/Mengli/mengliOrder/incomeItem/index';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { Title, selectWithUserLoad, IncomeItem,
    selectWithoutHttp, costBreakdownComponent, InvoiceAndContract,
    upAttachment, TagSelect, DetailTabs },
  mixins: [mobileCreate],
  data() {
    return {
      TAG_MODULES,
      isEdit: false,
      btnLoading: false,
      orderId: '',
      orderType: '',
      paramsObj: {
        attachment: [],
        ipAry: [],
        orderTime: new Date().setHours(0, 0, 0, 0),
        market: '', // 销售
        marketId: '', // 销售id
        marketObj: null,
        clientName: '',
        clientId: '',
        clientObj: null,
        licenseTime: [],
        licenseStartTime: '',
        licenseEndTime: '',
        authorizeTime: [],
        authorizeStartTime: '',
        authorizeEndTime: '',
        sharingModel: 0,
        minPrice: '',
        minPriceTotal: '',
        areaId: '', // 合作品类
        remark: '',
        incomeList: [],
        tag: [],
        signYear: new Date().getTime(),
        themeId: '', // 合作类型
        clientOriginId: '', // 客户来源
        matters: '', // 合作事项
        firstBDTime: ''// 首次BD时间
      },
      diffParams: { // 比较编辑了哪几个字段【修改字段权限】
        ipAry: [],
        licenseTime: [],
        sharingModel: 0,
        minPriceTotal: ''
      },
      rules: {
        orderTime: [{ required: true, trigger: 'change', validator: validateTime('请选择签约日期') }],
        ipAry: [{ required: true, trigger: 'change', validator: validateIp('请选择IP形象') }],
        market: [{ required: true, trigger: 'change', validator: validateIp('请选择商务负责人') }],
        clientName: [{ required: true, trigger: 'change', validator: validateNumber('请选择客户名称') }],
        clientOriginId: [{ required: true, trigger: 'change', validator: validateNumber('请选择客户来源') }],
        areaId: [{ required: true, trigger: 'change', validator: validateNumber('请选择合作品类') }],
        themeId: [{ required: true, trigger: 'change', validator: validateNumber('请选择合作类型') }],
        authorizeTime: [{ required: true, trigger: 'change', validator: validateTime('请选择合作期限') }],
        firstBDTime: [{ required: true, trigger: 'change', validator: validateTime('请选择首次BD日期') }],
        signYear: [{ required: true, trigger: 'change', validator: validateTime('请选择签约年度') }],
        sharingModel: [{ required: true, trigger: 'change', validator: validateNumber('请选择收入模式') }],
        costRate: [{ required: true, trigger: 'change', validator: validateNumber('请输入供应商分成比') }]
      },
      sharingModelOptions: [
        { value: 0, label: '固定' },
        { value: 1, label: '分成' },
        { value: 2, label: '保底+分成' }
      ],
      isFileDisabled: false,
      clientOrigin: [],
      area: [],
      theme: [],
      tabs: [
        { id: 0, name: '收入列表' },
        { id: 1, name: '成本列表' },
        { id: 2, name: '发票合同' }
      ],
      activeId: 0,
      loading: false,
      incomeListData: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      }
    };
  },
  computed: {
    rangeTime() {
      const licenseTime = this.paramsObj.licenseTime;
      if (licenseTime && licenseTime.length === 2) {
        const startTime = licenseTime[0];
        const endTime = licenseTime[1];
        return this.mathTime(startTime, endTime);
      }
      return '--';
    },
    mathMinPrice() {
      return (Number(this.paramsObj.minPriceTotal) / Number(this.rangeTime)).toFixed(2);
    },
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  created() {
    this.orderId = this.$route.params.id || '';
    this.orderType = this.$route.query.type || '0';
    if (this.orderId) {
      this.getDetail();
    }
    if (this.hasRouteAuth('mengli:iPOrder:periodsEdit') || !this.orderId) {
      this.isEdit = false;
    } else {
      this.isEdit = true;
    }
    this.getOrderConfig();
  },
  methods: {
    hasRouteAuth,
    getDetail() {
      this.loading = true;
      getipLicense({ id: this.orderId }).then(res => {
        if (res.data) {
          res.data.marketObj = {
            userName: res.data.market, id: res.data.marketId
          };
          res.data.clientObj = {
            clientName: res.data.clientName, id: res.data.clientId
          };
          if (res.data.minPrice) {
            res.data.minPrice = Number(res.data.minPrice) / 100;
          }
          if (res.data.minPriceTotal) {
            res.data.minPriceTotal = Number(res.data.minPriceTotal) / 100;
            this.diffParams.minPriceTotal = res.data.minPriceTotal;
          }
          if (res.data.licenseStartTime && res.data.licenseEndTime) {
            res.data.licenseStartTime = res.data.licenseStartTime * 1000;
            res.data.licenseEndTime = res.data.licenseEndTime * 1000;
            res.data.licenseTime = [res.data.licenseStartTime, res.data.licenseEndTime];
            this.diffParams.licenseTime = res.data.licenseTime;
          }
          if (res.data.authorizeStartTime && res.data.authorizeEndTime) {
            res.data.authorizeStartTime = res.data.authorizeStartTime * 1000;
            res.data.authorizeEndTime = res.data.authorizeEndTime * 1000;
            res.data.authorizeTime = [res.data.authorizeStartTime, res.data.authorizeEndTime];
            this.diffParams.authorizeTime = res.data.authorizeTime;
          }
          if (res.data.orderTime && res.data.orderTime.toString().length === 10) {
            res.data.orderTime = res.data.orderTime * 1000;
          }
          if (res.data.ipAry) {
            res.data.ipAry.forEach(j => {
              j.ipName = j.ipFigure;
              j.ipId = j.ipFigureId;
              j.ipNameAndSeries = `${j.ipFigure || '--'}/${j.ipSeries || '--'}`;
            });
            this.diffParams.ipAry = res.data.ipAry;
          }
          if (res.data.sharingModel) {
            this.diffParams.sharingModel = res.data.sharingModel;
          }
          // this.$refs.ipSupplier.initInfo(res.data.supplierAry); // 传值给成本信息
          if (this.$refs.costBreakdownRef && res.data.costBreakdown) this.$refs.costBreakdownRef.insertDetail(res.data.costBreakdown); // 传值给成本
          this.$nextTick(() => {
            if (this.$refs.ContractSelect) this.$refs.ContractSelect.setDefault(res.data.contract);
            if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(res.data.invoiceInfo);
          });
          this.paramsObj = res.data;
          this.loading = false;
          this.getIncomeList();
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    // 获取萌力星球订单配置项
    async getOrderConfig() {
      try {
        const res = await getOrderConfig();
        this.area = res.data.areaList;
        this.theme = res.data.themeList;
        this.clientOrigin = res.data.clientOriginList;
      } catch (error) {
        console.log(error);
      }
    },
    ipAryDiff(preAry, newAry) {
      if (preAry.length !== newAry.length) {
        return false;
      } else {
        const preIds = preAry.length ? preAry.map(it => it.ipId).sort().join() : '';
        const newIds = newAry.length ? newAry.map(it => it.ipId).sort().join() : '';
        return preIds === newIds;
      }
    },
    handleTheme(data) {
      this.paramsObj.theme = this.theme.find(it => it.id === data).name;
      this.paramsObj.themeId = data;
    },
    handleArea(data) {
      this.paramsObj.area = this.area.find(it => it.id === data).name;
      this.paramsObj.areaId = data;
    },
    beforeSubmit() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      const keyMap = ['ipAry', 'licenseTime', 'sharingModel', 'minPriceTotal'];
      const res = [];
      keyMap.map(it => {
        const preVal = this.diffParams[it] instanceof Array ? JSON.stringify(this.diffParams[it]) : this.diffParams[it];
        const newVal = paramsObj[it] instanceof Array ? JSON.stringify(paramsObj[it]) : paramsObj[it];
        if (it === 'ipAry') {
          const ipRes = this.ipAryDiff(this.diffParams[it], paramsObj[it]);
          if (!ipRes) {
            res.push(it);
          }
        } else if (it === 'minPriceTotal') {
          if (!(newVal === 0 && preVal === '') && preVal !== newVal) {
            res.push(it);
          }
        } else if (it === 'licenseTime') {
          if (!(!newVal && preVal === '[]') && preVal !== newVal) {
            res.push(it);
          }
        } else {
          if (preVal !== newVal) {
            res.push(it);
          }
        }
      });
      const nameMap = {
        ipAry: 'IP形象',
        licenseTime: '分期月份',
        sharingModel: '收入模式',
        minPriceTotal: '保底总额'
      };
      const message = res.map(it => nameMap[it]).join('/');
      if (res.length && this.$route.name === 'mengliOrderEdit') {
        this.$confirm(`${message} 字段存在修改，确认后订单分成信息将重新生成！`, '', {
          confirmButtonText: '确定', type: 'warning',
          showClose: false, center: true, iconClass: 'charge-icon',
          customClass: 'del-message del-message-cancel'
        }).then(() => {
          this.toSubmit();
        });
      } else {
        this.toSubmit();
      }
    },
    /**
     * 操作
     */
    toSubmit() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      if (paramsObj.licenseTime && paramsObj.licenseTime.length === 2) {
        paramsObj.licenseStartTime = paramsObj.licenseTime[0].toString().length === 13 ? Math.floor(paramsObj.licenseTime[0] / 1000) : paramsObj.licenseTime[0];
        paramsObj.licenseEndTime = paramsObj.licenseTime[1].toString().length === 13 ? Math.floor(paramsObj.licenseTime[1] / 1000) : paramsObj.licenseTime[1];
      }
      if (paramsObj.authorizeTime.length === 2) {
        paramsObj.authorizeStartTime = paramsObj.authorizeTime[0].toString().length === 13 ? Math.floor(paramsObj.authorizeTime[0] / 1000) : paramsObj.authorizeTime[0];
        paramsObj.authorizeEndTime = paramsObj.authorizeTime[1].toString().length === 13 ? Math.floor(paramsObj.authorizeTime[1] / 1000) : paramsObj.authorizeTime[1];
      }
      paramsObj.firstBDTime = Math.floor(paramsObj.firstBDTime / 1000);
      paramsObj.signYear = Math.floor(paramsObj.signYear / 1000);
      if (paramsObj.orderTime && paramsObj.orderTime.toString().length === 13) paramsObj.orderTime = Math.floor(paramsObj.orderTime / 1000);
      const priceField = ['minPrice', 'minPriceTotal']; // 价格的字段
      this.handelPrice(paramsObj, priceField);
      paramsObj.costRate = Number(paramsObj.costRate);
      paramsObj.minPrice = Number(paramsObj.minPrice);
      paramsObj.minPriceTotal = Number(paramsObj.minPriceTotal);
      const discountInfoParams = this.$refs.costBreakdownRef ? this.$refs.costBreakdownRef.list : {};
      // discountInfoParams.costList.map(item => {
      //   item.taxCost = item.taxCost || item.taxCost === 0 ? item.taxCost * 100 : null;
      //   return item;
      // });
      paramsObj.costBreakdown = discountInfoParams;
      // const supplierAry = this.$refs.ipSupplier.getParams();
      const relatedIds = this.getRelatedIds();
      paramsObj.invoiceIds = relatedIds.invoiceIds;
      paramsObj.contractIds = relatedIds.contractIds;
      this.$refs.formRef.validate(valid => {
        // this.$refs['ipSupplier'].validateForm().then(res => { // 成本信息表单验证
        //   if (supplierAry === 'error') return;
        //   paramsObj.supplierAry = supplierAry;
        // });
        if (valid) {
          if (this.orderId) {
            this.edit(paramsObj);
          } else {
            this.add(paramsObj);
          }
        } else {
          return false;
        }
      });
    },
    getFormPromise(form) {
      return new Promise(resolve => {
        form.validate(res => {
          resolve(res);
        });
      });
    },
    edit(params) {
      params.id = this.orderId;
      this.btnLoading = true;
      editMengliIpOrder(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toDetail();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      createMengliIpOrder(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toBack();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    numberInputChange(key) {
      if (this.paramsObj[key]) this.paramsObj[key] = Number(this.paramsObj[key]).toFixed(2);
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 0;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    },
    toDetail() {
      if (!this.orderId) return;
      this.$router.push({
        name: 'mengliOrderDetail',
        params: { id: this.orderId },
        query: { type: 0 }
      });
    },
    // 获取合同和发票
    getRelatedIds() {
      const contractSelect = this.$refs.ContractSelect;
      const invoiceSelect = this.$refs.InvoiceSelect;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(',')
      };
    },
    /**
     * 获取下拉数据
     */
    // 获取ip形象
    getipFigure() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.ipName = '';
          if (params.userName) params.ipName = params.userName;
          delete params.userName;
          getIpImageList(params).then(res => {
            if (res.data && res.data.items) {
              res.data.items.forEach(j => {
                if (!j.ipFigure)j.ipFigure = j.ipName;
                if (!j.ipFigureId)j.ipFigureId = j.ipId;
                j.ipNameAndSeries = `${j.ipName || '--'}/${j.ipSeriesName || '--'}`;
              });
            }
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    getClient() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.clientName = '';
          if (params.userName) params.clientName = params.userName;
          getClientList(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    getSuppliers() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.keyword = '';
          if (params.userName) params.keyword = params.userName;
          getMengliSuppliers(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    /**
     * change 事件
     */
    ipFigureChange(item) {
      // this.paramsObj.ipFigure = item.userName;
      // this.paramsObj.ipFigureId = item.id;
    },
    clientNameChange(item) {
      this.paramsObj.clientName = item.clientName;
      this.paramsObj.clientId = item.id;
    },
    marketChange(item) {
      this.paramsObj.market = item.userName;
      this.paramsObj.marketId = item.id;
    },
    /**
     * 工具
     */
    // 计算期数
    mathTime(startTime, endTime) {
      const start = this.getFullTime(startTime);
      const end = this.getFullTime(endTime);
      // if (start.year === end.year && start.month === end.month && start.day === end.day) {
      //   return 1;
      // }
      const diffYear = end.year - start.year;
      const diffMonth = end.month - start.month;
      return diffYear * 12 + diffMonth + 1;
      // // 同年-不同月
      // if ((start.year - end.year) === 0) {
      //   let time = 0;
      //   const diffMonth = end.month - start.month;
      //   if (start.day < end.day) {
      //     time++;
      //   }
      //   return time + diffMonth;
      // } else { // 不同年
      //   const diffYear = end.year - start.year;
      //   let time = 0;
      //   // const startMonth = 12 - start.month; // 时间推到当年12月
      //   // const endMonth = 12 - end.month; // 透支时间，时结束时间到达当年12月，总时间需要减去
      //   const diffMonth = end.month - start.month;
      //   if (start.day < end.day) {
      //     time++;
      //   }
      //   return time + (diffYear * 12) + diffMonth;
      // }
    },
    getFullTime(time, diff = 0) {
      const timeDate = new Date(time + diff);
      const year = timeDate.getFullYear();
      const month = timeDate.getMonth() + 1;
      const day = timeDate.getDate(); // 几号
      return {
        year, month, day
      };
    },
    handelPrice(params, priceField = []) {
      for (const key in params) {
        if (priceField.includes(key) && Number(params[key])) {
          const numberArr = params[key].toString().split('.');
          if (numberArr && numberArr.length) {
            if (numberArr.length === 1) { // 说明是整数，不用担心精度丢失
              params[key] = Number(params[key]) * 100;
            } else if (numberArr.length === 2) {
              let floatPart = numberArr[1];
              floatPart = floatPart.length >= 2 ? floatPart[0] + floatPart[1] : floatPart + 0;
              params[key] = Number(numberArr[0] + floatPart);
            }
          }
        }
      }
    },
    /**
     * 收入项
     */
    editIcomeItem(params, listParams) {
      editIpIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.freshIncomeData(listParams);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    addIcomeItem(params, listParams) {
      params.mengliId = this.orderId;
      addIpIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.freshIncomeData(listParams);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    deleteIcomeItem(params, listParams) {
      deleteIpIncomeList(params).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.freshIncomeData(listParams);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    freshIncomeData(data) {
      this.getIncomeList(data);
      // getipLicense({ id: this.orderId }).then(res => {
      //   if (res.data) {
      //     this.paramsObj.incomeList = res.data.incomeList;
      //   }
      // });
    },
    // 上传文件
    upProgress() {
      this.createLoading = true;
    },
    complateSetData({ data, fileName }) {
      this.createLoading = false;
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.paramsObj && this.paramsObj.attachment && this.paramsObj.attachment.length > 0) {
        this.paramsObj.attachment.unshift(fileList);
      } else {
        this.paramsObj.attachment = [fileList];
      }
    },
    removeFileList({ file, index }) {
      this.paramsObj.attachment.splice(index, 1);
    },
    getIncomeList(params = {}) {
      if (!params.page) params.page = 1;
      if (!params.perPage) params.perPage = 20;
      getIpIncomeList({ id: this.orderId, ...params }).then(res => {
        if (res.code === 200) {
          this.incomeListData = res.data;
          this.paramsObj.incomeList = res.data.items;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.width240 {
  width: 240px;
}
.create-ip-order {
  background:rgba(255,255,255,1);
  padding: 24px;
  padding-bottom: 80px;
	min-height: calc(100vh - 64px);
}
.create-ip-order-form {
  &::v-deep {
    .el-cascader {
      width: 100%;
    }
    .el-range-editor {
      /* .el-range-input {
        width: 90px;
      } */
      .el-range-separator {
        width: 20px;
      }
    }
  }
}
.width-long-item {
  &::v-deep {
    .el-select-dropdown{
      overflow: hidden;
    }
    .el-select-dropdown__item {
      max-width: 100%;
    }
  }
}
.one-cell {
  width: 100%;
  display: flex;
}
.tip-right {
  position: absolute;
  left: 0;
  white-space: nowrap;
  top: 28px;
  line-height: 32px;
  height: 32px;
  color: #999999;
}
.tip-bottom {
  position: absolute;
  left: 0;
  line-height: 1.2;
}
.select-related-container {
  margin-top:30px;
  padding: 0 !important;
  &::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
  }
}
</style>
<style lang="scss">
.create-ip-order {
  .el-row .el-card {
    border: none;
    background: #fff;
    border-radius: 0;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
}
</style>
